﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using DocumentGain.model;
using DocumentGain;
using DocumentGain.dal;
using System.Configuration;
using System.Threading;


namespace DocumentGain
{
    public partial class leading_特殊数据处理 : Form
    {
        private delegate void SetControlTextCallback(Control o, string text); // 设置控件文本的委托

        private bool t = true;

        private string _message = "";

        private string _allmessage = "";

        string LogDate = "";

        //InterfaceService.creatflow_xmClient sjint = new InterfaceService.creatflow_xmClient();

        InterfaceServiceTest.creatflow_xmClient sjint = new InterfaceServiceTest.creatflow_xmClient();

        public leading_特殊数据处理()
        {
            InitializeComponent();

        }

        private void SetControlText(Control o, string text)
        {
            try
            {
                if (o.InvokeRequired)
                {
                    SetControlTextCallback d = new SetControlTextCallback(SetControlText);
                    this.Invoke(d, o, text);
                }
                else
                {
                    _allmessage = text + "\r\n" + _allmessage;
                    o.Text = _allmessage;
                }
            }
            catch { }
        }


        public string Replace(string str)
        {
            return str.Replace("'", "");
        }

        public void DataLeadingin(object o)
        {
            if (true)
            {
                //关注记录
                
                string BeginTime = ConfigurationManager.AppSettings["BeginTime"];
                string EndTime = ConfigurationManager.AppSettings["EndTime"];
                string DocType = ConfigurationManager.AppSettings["type"];
                string appdbpath = ConfigurationManager.AppSettings["dbpath"];
                string isImportTakecare = ConfigurationManager.AppSettings["isImportTakecare"];

                DateTime dt1 = Convert.ToDateTime(BeginTime);
                DateTime dt2 = Convert.ToDateTime(EndTime);
                int Month = (dt2.Year - dt1.Year) * 12 + (dt2.Month - dt1.Month);

                StringBuilder sb = new StringBuilder();
                Service service = new Service();

                if (isImportTakecare == "1")
                {
                    string sql = @"delete TakeCare";
                    sqlHelp.ExecuteSql(sql);
                    string[] tempArr = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
                    foreach (string tempStr in tempArr)
                    {
                        string personJson = "{\"info\":[{\"head\":\"" + tempStr + "\"}]}";
                        //Import12(personJson, service, sb);
                    }
                }
                

                //for (int i = 0; i < Month; i++)
                //{
                //    string Date = Convert.ToDateTime(BeginTime).AddMonths(i).ToString("yyyy-MM-dd");
                //    LogDate = Convert.ToDateTime(BeginTime).AddMonths(i).ToString("yyyyMM");
                //    _message = "开始获取" + LogDate + "数据";
                //    WriteLogFile(_message);
                //    string _year = Convert.ToDateTime(Date).ToString("yyyy");
                //    string _month = Convert.ToDateTime(Date).ToString("MM");
                //    //Type 0:表示获取所有普通模块的所有文档 1:标示获取所有公文类模块的所有文档
                //    string type = "0";
                //    if (DocType == "公文类")
                //    {
                //        type = "1";
                //    }
                //    else if (DocType == "非公文类")
                //    {
                //        type = "0";
                //    }

                //    string personJson = "{\"info\":[{\"type\":\"" + type + "\",\"year\":\"" + _year + "\",\"month\":\"" + _month + "\"}]}";
                //    string result = sjint.GETALLDOCS(personJson);
                //    //string result = sjint.GETALLDOCSTRASH(personJson);
                //    JObject jo = (JObject)JsonConvert.DeserializeObject(result);
                //    if (jo["data"][0]["result"].ToString() == "success")
                //    {
                //        string result_info = jo["data"][1]["info"].ToString();
                //        JArray ja = (JArray)JsonConvert.DeserializeObject(result_info);
                //        _message = LogDate + "共有" + ja.Count + "条数据,开始导入!";
                //        WriteLogFile(_message);
                //        //Thread.Sleep(100);
                //        for (int n = 0; n < ja.Count; n++)
                //        //for (int n = 0; n < 10; n++)
                //        {
                //            //文档ID
                //            Guid DocumentID = Guid.NewGuid();
                //            //获取到的ID
                //            string unid = ja[n]["unid"].ToString();
                //            //获取到的数据路径
                //            string dbpath = ja[n]["dbpath"].ToString();
                //            string qicaorq = ja[n]["qicaorq"].ToString();
                //            string flowtype = ja[n]["flowtype"].ToString();

                //            if (true)
                //            {
                //                //输入参数
                //                personJson = "{\"info\":[{\"dbpath\":\"" + dbpath + "\",\"unid\":\"" + unid + "\"}]}";
                //                //personJson = "{\"info\":[{\"dbpath\":\"gwlz/ioboard.nsf\",\"unid\":\"636A8F35AAF0CF52482581AA002C8CF6\"}]}";                  
                //                //文档ID
                //                //if (Import0(service, unid, personJson, qicaorq, dbpath, flowtype, type))
                //                if (true)
                //                {
                //                    //流转意见
                //                    //Import1(unid, personJson, service, sb);
                //                    //文档权限（管理员、办理人、知会人、其他）
                //                    //Import2(unid, personJson, service, sb);
                //                    //文件（正文、附件）
                //                    //Import3(unid, personJson, service, sb);
                //                    //表单信息
                //                    //Import4(unid, personJson, service, sb);
                //                    //流转记录
                //                     //Import5(unid, personJson, service, sb);

                //                    //知会记录
                //                    //Import10(unid, personJson, service, sb);

                //                    //if (type == "1")
                //                    //{
                //                        //公文修改记录
                //                        //Import6(unid, personJson, service, sb);
                //                        //关联文档
                //                        //Import7(unid, personJson, service, sb);
                //                        //公文评价
                //                        //Import8(unid, personJson, service, sb);
                //                        //提醒记录
                //                        //Import9(unid, personJson, service, sb);
                //                        //发文跟踪
                //                        //if (personJson.IndexOf("fwgl") > -1)
                //                        //{
                //                        //    Import11(unid, personJson, service, sb);
                //                        //}
                //                    //}

                //                }
                //            }
                //            //Thread.Sleep(100);
                //        }
                //    }
                //    _message = Date + "数据导入完成！";
                //    WriteLogFile(_message);
                //}

                WriteLogFile("数据导入完成" + DateTime.Now.ToString());
                t = false;
            }
        }

        public void DataLeadinginEx(object o)
        {

            StringBuilder sb = new StringBuilder();
            Service service = new Service();

            //string isImportTakecare = ConfigurationManager.AppSettings["isImportTakecare"];

            //if (isImportTakecare == "1")
            //{
            //    string sqlTakeCare = "delete TakeCare";
            //    sqlHelp.ExecuteSql(sqlTakeCare);

            //    string[] tempArr = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
            //    foreach (string tempStr in tempArr)
            //    {
            //        string personJson = "{\"info\":[{\"head\":\"" + tempStr + "\"}]}";
            //        Import12(personJson, service, sb);
            //    }
            //}

            string sql = ConfigurationManager.AppSettings["sql"];
            DataTable dta = sqlHelp.Query(sql).Tables[0];

            _message = LogDate + "共有" + dta.Rows.Count + "条数据,开始导入!";
            WriteLogFile(_message);
            for (int n = 0; n < dta.Rows.Count; n++)
            {

                MessageShow("开始导入"+n+"条数据");
                //文档ID
                Guid DocumentID = Guid.NewGuid();
                //获取到的ID
                string unid = dta.Rows[n]["documentid"].ToString();
                //获取到的数据路径
                string dbpath = dta.Rows[n]["dbpath"].ToString();
                string qicaorq = dta.Rows[n]["qicaorq"].ToString();
                string flowtype = dta.Rows[n]["flowtype"].ToString();

                if (true)
                {
                    //输入参数
                    string personJson = "{\"info\":[{\"dbpath\":\"" + dbpath + "\",\"unid\":\"" + unid + "\"}]}";
                    //string personJson = "{\"info\":[{\"dbpath\":\"gwlz/dep11/bmlxd_11.nsf\",\"unid\":\"4BD0F4FB7EAB95BC48258194000643A6\"}]}";                  
                    //文档ID
                    //if (Import0(service, unid, personJson, qicaorq, dbpath, flowtype, type))
                    if (true)
                    {
                        //流转意见
                        //Import1(unid, personJson, service, sb);
                        //文档权限（管理员、办理人、知会人、其他）
                        //Import2(unid, personJson, service, sb);
                        //文件（正文、附件）
                        //Import3(unid, personJson, service, sb);
                        //表单信息
                        //Import4(unid, personJson, service, sb);
                        //流转记录
                        //Import5(unid, personJson, service, sb);

                        //知会记录
                        Import10(unid, personJson, service, sb);

                        //if (type == "1")
                        //{
                        //公文修改记录
                        //Import6(unid, personJson, service, sb);
                        //关联文档
                        //Import7(unid, personJson, service, sb);
                        //公文评价
                        //Import8(unid, personJson, service, sb);
                        //提醒记录
                        //Import9(unid, personJson, service, sb);
                        //发文跟踪
                        //Import11(unid, personJson, service, sb);
                        //Import13(unid, personJson, service, sb);
                    }

                    //Thread.Sleep(100);
                }
            }
            _message = "数据导入完成！";
            WriteLogFile(_message);



            WriteLogFile("数据导入完成" + DateTime.Now.ToString());
            t = false;
        }


        /// <summary>
        /// 关注数据
        /// </summary>
        //protected void Import12(string personJson, Service service, StringBuilder sb)
        //{
        //    try
        //    {
        //        string TakeCare = sjint.GETGZINFO(personJson);
        //        JObject jo_TakeCare = (JObject)JsonConvert.DeserializeObject(TakeCare);
        //        if (jo_TakeCare["data"][0]["result"].ToString() == "success")
        //        {
        //            string TakeCare_info = jo_TakeCare["data"][1]["info"].ToString();
        //            JArray ja_TakeCare = (JArray)JsonConvert.DeserializeObject(TakeCare_info);
        //            //JObject ja_AssociatedDocument = (JObject)JsonConvert.DeserializeObject(AssociatedDocument);
        //            if (ja_TakeCare.Count > 0)
        //            {

        //                for (int i = 0; i < ja_TakeCare.Count; i++)
        //                {
        //                    bool ishave = false;
        //                    TakeCare takecare = new TakeCare();
        //                    takecare.DocumentID = ja_TakeCare[i]["strID"].ToString();
        //                    takecare.TakeCareID = Guid.NewGuid();

        //                    if (ja_TakeCare[i]["strTITLE"] != null && ja_TakeCare[i]["strTITLE"].ToString() != "")
        //                    {
        //                        takecare.strName = ja_TakeCare[i]["strTITLE"].ToString().Replace("待办", "").Replace("待阅", "");
        //                        if (takecare.strName.Trim().Length > 0)
        //                        {
        //                            ishave = true;
        //                        }
        //                    }

        //                    DateTime tempDt = new DateTime();

        //                    if (DateTime.TryParse(ja_TakeCare[i]["strTIME"].ToString().Substring(0, 19), out tempDt))
        //                    {
        //                        takecare.TakeCareTime = tempDt;
        //                    }

        //                    if (ishave)
        //                    {
        //                        service.AddTakeCare(takecare);
        //                    }
        //                }
        //                _message = "关注 导入成功!";
        //                MessageShow(_message);
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        _message = "关注 导入失败!" + personJson + "|" + ex.Message;
        //        WriteLogFile(_message);
        //    }
        //}



        protected void Import13(string DocumentID, string personJson, Service service, StringBuilder sb)
        {
            //{"data":[{"result":"success"},{"info":[{"mainkey":""}]}]}
            try
            {
                string Countersign = sjint.GETHQIDZINFO(personJson);
                JObject jo_Countersign = (JObject)JsonConvert.DeserializeObject(Countersign);
                if (jo_Countersign["data"][0]["result"].ToString() == "success")
                {
                    string Countersign_info = jo_Countersign["data"][1]["info"].ToString();
                    JArray ja_Countersign = (JArray)JsonConvert.DeserializeObject(Countersign_info);
                    //JObject ja_AssociatedDocument = (JObject)JsonConvert.DeserializeObject(AssociatedDocument);
                    if (ja_Countersign.Count > 0)
                    {

                        for (int i = 0; i < ja_Countersign.Count; i++)
                        {
                            bool ishave = false;
                            Countersign countersign = new Countersign();
                            countersign.DocumentID = DocumentID;
                            countersign.CountersignID = Guid.NewGuid();

                            if (ja_Countersign[i]["mainkey"] != null && ja_Countersign[i]["mainkey"].ToString() != "")
                            {
                                countersign.mainkey = ja_Countersign[i]["mainkey"].ToString();
                                if (countersign.mainkey.Trim().Length > 0)
                                {
                                    string sql = "select mainkey from [dbo].[Countersign] where mainkey = '" + countersign.mainkey + "'";
                                    DataTable dt = sqlHelp.Query(sql).Tables[0];
                                    if (dt.Rows.Count == 0)
                                    {
                                        ishave = true;
                                    }
                                }
                                countersign.DEP = ja_Countersign[i]["DEP"].ToString();

                                countersign.user = ja_Countersign[i]["user"].ToString();

                            }

                            if (ishave)
                            {
                                service.AddCountersign(countersign);
                            }
                        }
                        _message = "会签 导入成功!";
                        MessageShow(_message);
                    }
                }
            }
            catch (Exception ex)
            {
                _message = "会签 导入失败!" + personJson + "|" + ex.Message;
                WriteLogFile(_message);
            }
            
            
        }
        




        private void button1_Click(object sender, EventArgs e)
        {
            //ThreadPool.QueueUserWorkItem(DataLeadingin);
        }


        protected bool Import0(Service service, string key, string cs, string qicaorq, string dbpath, string flowtype, string documenttype)
        {
            try
            {
                MainDocument m = new MainDocument();
                m.DocumentID = key;
                m.qicaorq = qicaorq;
                m.dbpath = dbpath;
                m.flowtype = flowtype;
                m.DocumentType = documenttype;
                service.AddMainDocument(m);
                return true;
            }
            catch (Exception ex)
            {
                Thread.Sleep(100);
                _message = ex.Message;
                MessageShow(_message);
                return false;
            }
        }

        /// <summary>
        /// 获取流转意见
        /// </summary>
        /// <param name="DocumentID"></param>
        /// <param name="personJson"></param>
        /// <param name="service"></param>
        /// <param name="sjint"></param>
        /// <param name="sb"></param>
        protected void Import1(string DocumentID, string personJson, Service service, StringBuilder sb)
        {
            try
            {

                //personJson = "{\"info\":[{\"dbpath\":\"gwlz/wwzxhf.nsf\",\"unid\":\"F352914E4363C0A5482580B3000ECC00\"}]}";
                string Auditing = sjint.GETAPPROVALINFO(personJson);

                JObject jo_Auditing = (JObject)JsonConvert.DeserializeObject(Auditing);
                if (jo_Auditing["data"][0]["result"].ToString() == "success")
                {
                    string Auditing_info = jo_Auditing["data"][1]["info"].ToString();
                    JArray ja_Auditing = (JArray)JsonConvert.DeserializeObject(Auditing_info);
                    if (ja_Auditing.Count > 0)
                    {
                        Auditing auditing = new Auditing();
                        auditing.DocumentID = DocumentID;
                        for (int i = 0; i < ja_Auditing.Count; i++)
                        {
                            auditing.AuditingID = Guid.NewGuid();
                            //处理人
                            if (ja_Auditing[i]["user"] != null)
                            { auditing.User = ja_Auditing[i]["user"].ToString(); }
                            //处理人日期
                            if (ja_Auditing[i]["date"] != null)
                            { auditing.date = Convert.ToDateTime(ja_Auditing[i]["date"].ToString()); }
                            //意见
                            if (ja_Auditing[i]["opinion"] != null)
                            { auditing.opinion = Replace(ja_Auditing[i]["opinion"].ToString()); }
                            //状态
                            if (ja_Auditing[i]["status"] != null)
                            { auditing.status = ja_Auditing[i]["status"].ToString(); }
                            //环节号
                            //if (ja_Auditing[i]["num"] != null)
                            //{ auditing.num = Convert.ToInt32(ja_Auditing[i]["num"].ToString()); }
                            //else { auditing.num = 0; }
                            if (ja_Auditing[i]["num"] != null)
                            { auditing.num = Convert.ToInt32(ja_Auditing[i]["num"].ToString()); }
                            else
                            {
                                auditing.num = i;
                            }

                            service.AddAuditing(auditing);
                        }
                        _message = "流转意见导入成功!";
                        MessageShow(_message);
                    }
                }
            }
            catch (Exception ex)
            {
                _message = "流转意见导入失败!" + personJson + "|" + ex.Message;
                WriteLogFile(_message);
            }
        }

        /// <summary>
        /// 文档权限（管理员、办理人、知会人、其他）
        /// </summary>
        /// <param name="DocumentID"></param>
        /// <param name="personJson"></param>
        /// <param name="service"></param>
        /// <param name="sjint"></param>
        /// <param name="sb"></param>
        protected void Import2(string DocumentID, string personJson, Service service, StringBuilder sb)
        {
            try
            {
                string Rules = sjint.GETQXINFO(personJson);

                JObject jo_Rules = (JObject)JsonConvert.DeserializeObject(Rules);
                if (jo_Rules["data"][0]["result"].ToString() == "success")
                {
                    string Rules_info = jo_Rules["data"][1]["info"].ToString();
                    JArray ja_Rules = (JArray)JsonConvert.DeserializeObject(Rules_info);
                    if (ja_Rules.Count > 0)
                    {
                        Rules rules = new Rules();
                        rules.DocumentID = DocumentID;
                        for (int i = 0; i < ja_Rules.Count; i++)
                        {
                            rules.RulesID = Guid.NewGuid();
                            if (ja_Rules[i]["manager"] != null)
                            {
                                if (ja_Rules[i]["manager"].ToString() != "")
                                {
                                    //模块管理员
                                    rules.manager = ja_Rules[i]["manager"].ToString();
                                    //部门管理员（文书）
                                    rules.docmanager = ja_Rules[i]["manager"].ToString();
                                    //知会人
                                    if (ja_Rules[i]["readuser"] != null)
                                    { rules.readuser = ja_Rules[i]["readuser"].ToString(); }
                                    //处理人
                                    if (ja_Rules[i]["todouser"] != null)
                                    { rules.todouser = ja_Rules[i]["todouser"].ToString(); }
                                    //if (ja_Rules[0]["docmanager"] != null)
                                    //{ rules.docmanager = ja_Rules[0]["manager"].ToString(); }
                                    service.AddRules(rules);
                                }
                            }
                        }
                        _message = "文档权限导入成功!";
                        MessageShow(_message);
                    }
                }
            }
            catch (Exception ex)
            {
                _message = "文档权限导入失败!" + personJson + "|" + ex.Message;
                WriteLogFile(_message);
            }
        }

        /// <summary>
        /// 获取文件（正文、附件）
        /// </summary>
        /// <param name="DocumentID"></param>
        /// <param name="personJson"></param>
        /// <param name="service"></param>
        /// <param name="sjint"></param>
        /// <param name="sb"></param>
        protected void Import3(string DocumentID, string personJson, Service service, StringBuilder sb)
        {
            try
            {
                string File = sjint.GETATTINFO(personJson);

                JObject jo_File = (JObject)JsonConvert.DeserializeObject(File);
                if (jo_File["data"][0]["result"].ToString() == "success")
                {
                    string File_info = jo_File["data"][1]["info"].ToString();
                    JArray ja_File = (JArray)JsonConvert.DeserializeObject(File_info);
                    if (ja_File.Count > 0)
                    {
                        DocumentGain.model.File file = new DocumentGain.model.File();
                        file.DocumentID = DocumentID;
                        for (int i = 0; i < ja_File.Count; i++)
                        {
                            file.fileID = Guid.NewGuid();
                            if (ja_File[i]["filename"] != null)
                            {
                                if (ja_File[i]["filename"].ToString() != "")
                                {
                                    //附件名称
                                    file.filename = ja_File[i]["filename"].ToString();
                                    //附件路径
                                    if (ja_File[i]["filepath"] != null)
                                    { file.filepath = ja_File[i]["filepath"].ToString(); }

                                    if (ja_File[i]["flagftype"] != null)
                                    { file.flagftype = ja_File[i]["flagftype"].ToString(); }

                                    if (ja_File[i]["flagfix"] != null)
                                    { file.flagfix = ja_File[i]["flagfix"].ToString(); }

                                    if (ja_File[i]["fixrecord"] != null)
                                    { file.fixrecord = ja_File[i]["fixrecord"].ToString(); }

                                    service.AddFile(file);
                                }
                            }
                        }
                        _message = "文件 导入成功!";
                        MessageShow(_message);
                    }
                }
            }
            catch (Exception ex)
            {
                //sb.Append(string.Format("导入文件（正文、附件）报错，错误：{0}", ex.Message));
                _message = "文件 导入失败!" + personJson + "|" + ex.Message;
                WriteLogFile(_message);
            }
        }

        /// <summary>
        /// 获取表单信息
        /// </summary>
        /// <param name="DocumentID"></param>
        /// <param name="personJson"></param>
        /// <param name="service"></param>
        /// <param name="sjint"></param>
        /// <param name="sb"></param>
        protected void Import4(string DocumentID, string personJson, Service service, StringBuilder sb)
        {
            try
            {
                //{"info":[{"dbpath":"gwlz/qjgl.nsf","unid":"9C35F77CB60A05D8482580B300339412"}]}
                //personJson = "{\"info\":[{\"dbpath\":\"gwlz/qjgl.nsf\",\"unid\":\"9C35F77CB60A05D8482580B300339412\"}]}";
                string Tabulation = sjint.GETFORMINFO(personJson);
                if (Tabulation != null)
                {
                    JObject jo_Tabulation = (JObject)JsonConvert.DeserializeObject(Tabulation);
                    if (jo_Tabulation["data"][0]["result"].ToString() == "success")
                    {
                        string Tabulation_info = jo_Tabulation["data"][1]["info"].ToString();
                        JArray ja_Tabulation = (JArray)JsonConvert.DeserializeObject(Tabulation_info);
                        if (ja_Tabulation != null)
                        {
                            if (ja_Tabulation.Count > 0)
                            {
                                Tabulation tabulation = new Tabulation();

                                tabulation.DocumentID = DocumentID;
                                for (int n = 0; n < ja_Tabulation.Count; n++)
                                {
                                    tabulation.TabulationID = Guid.NewGuid();
                                    //域名
                                    if (ja_Tabulation[n]["name"] != null)
                                    { tabulation.name = ja_Tabulation[n]["name"].ToString(); }
                                    //域说明
                                    if (ja_Tabulation[n]["cname"] != null)
                                    { tabulation.cname = ja_Tabulation[n]["cname"].ToString(); }
                                    //域值
                                    if (ja_Tabulation[n]["value"] != null)
                                    { tabulation.value = ja_Tabulation[n]["value"].ToString(); }
                                    service.AddTabulation(tabulation);
                                }
                                _message = "表单信息 导入成功!";
                                MessageShow(_message);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //sb.Append(string.Format("导入表单信息报错，错误：{0}", ex.Message));
                _message = "表单信息 导入失败!" + personJson + "|" + ex.Message;
                WriteLogFile(_message);
            }
        }

        /// <summary>
        /// 获取流转记录
        /// </summary>
        /// <param name="DocumentID"></param>
        /// <param name="personJson"></param>
        /// <param name="service"></param>
        /// <param name="sjint"></param>
        /// <param name="sb"></param>
        protected void Import5(string DocumentID, string personJson, Service service, StringBuilder sb)
        {
            try
            {
                string AuditingRecord = sjint.GETAPPROVEFLOWINFO(personJson);
                JObject jo_AuditingRecord = (JObject)JsonConvert.DeserializeObject(AuditingRecord);
                if (jo_AuditingRecord["data"][0]["result"].ToString() == "success")
                {
                    string AuditingRecord_info = jo_AuditingRecord["data"][1]["info"].ToString();
                    JArray ja_AuditingRecord = (JArray)JsonConvert.DeserializeObject(AuditingRecord_info);
                    if (ja_AuditingRecord.Count > 0)
                    {
                        AuditingRecord auditingrecord = new AuditingRecord();
                        auditingrecord.DocumentID = DocumentID;
                        for (int i = 0; i < ja_AuditingRecord.Count; i++)
                        {
                            auditingrecord.AuditingRecordID = Guid.NewGuid();
                            //处理人
                            if (ja_AuditingRecord[i]["user"] != null)
                            { auditingrecord.User = ja_AuditingRecord[i]["user"].ToString(); }
                            //处理人日期
                            if (ja_AuditingRecord[i]["date"] != null)
                            { auditingrecord.date = Convert.ToDateTime(ja_AuditingRecord[i]["date"].ToString()); }
                            //状态
                            if (ja_AuditingRecord[i]["status"] != null)
                            { auditingrecord.status = ja_AuditingRecord[i]["status"].ToString(); }
                            //下一步状态
                            if (ja_AuditingRecord[i]["nextstatus"] != null)
                            { auditingrecord.NextStatus = ja_AuditingRecord[i]["nextstatus"].ToString(); }
                            //下一步处理人
                            if (ja_AuditingRecord[i]["nextuser"] != null)
                            { auditingrecord.NextUser = ja_AuditingRecord[i]["nextuser"].ToString(); }
                            //转处理人
                            if (ja_AuditingRecord[i]["forwarduser"] != null)
                            { auditingrecord.forwarduser = ja_AuditingRecord[i]["forwarduser"].ToString(); }
                            //环节号
                            if (ja_AuditingRecord[i]["num"] != null)
                            { auditingrecord.num = Convert.ToInt32(ja_AuditingRecord[i]["num"].ToString()); }
                            else
                            {
                                auditingrecord.num = i;
                            }

                            service.AddAuditingRecord(auditingrecord);
                        }
                        _message = "流转记录 导入成功!";
                        MessageShow(_message);
                    }
                }

            }
            catch (Exception ex)
            {
                //sb.Append(string.Format("导入流转记录报错，错误：{0}", ex.Message));
                _message = "流转记录 导入失败!" + personJson + "|" + ex.Message;
                WriteLogFile(_message);
            }
        }

        /// <summary>
        /// 附件修改记录
        /// </summary>
        /// <param name="DocumentID"></param>
        /// <param name="personJson"></param>
        /// <param name="service"></param>
        /// <param name="sjint"></param>
        /// <param name="sb"></param>
        protected void Import6(string DocumentID, string personJson, Service service, StringBuilder sb)
        {
            try
            {
                string AmendantRecord = sjint.GETXGJLINFO(personJson);
                JObject jo_AmendantRecord = (JObject)JsonConvert.DeserializeObject(AmendantRecord);
                if (jo_AmendantRecord["data"][0]["result"].ToString() == "success")
                {
                    string AmendantRecord_info = jo_AmendantRecord["data"][1]["info"].ToString();
                    JArray ja_AmendantRecord = (JArray)JsonConvert.DeserializeObject(AmendantRecord_info);
                    if (ja_AmendantRecord.Count > 0)
                    {
                        AmendantRecord amendantrecord = new AmendantRecord();
                        amendantrecord.DocumentID = DocumentID;
                        for (int i = 0; i < ja_AmendantRecord.Count; i++)
                        {
                            bool ishave = false;

                            amendantrecord.AmendantRecordID = Guid.NewGuid();
                            //ip地址
                            if (ja_AmendantRecord[i]["strip"] != null && ja_AmendantRecord[i]["strip"].ToString() != "")
                            { amendantrecord.strip = ja_AmendantRecord[i]["strip"].ToString(); ishave = true; }
                            //修改描述
                            if (ja_AmendantRecord[i]["strxgms"] != null && ja_AmendantRecord[i]["strxgms"].ToString() != "")
                            { amendantrecord.strxgms = ja_AmendantRecord[i]["strxgms"].ToString(); ishave = true; }
                            //修改人
                            if (ja_AmendantRecord[i]["strxgr"] != null && ja_AmendantRecord[i]["strxgr"].ToString() != "")
                            { amendantrecord.strxgr = ja_AmendantRecord[i]["strxgr"].ToString(); ishave = true; }
                            //修改时间
                            if (ja_AmendantRecord[i]["strxgsj"] != null && ja_AmendantRecord[i]["strxgsj"].ToString() != "")
                            { amendantrecord.strxgsj = ja_AmendantRecord[i]["strxgsj"].ToString(); ishave = true; }
                            //修改内容
                            if (ja_AmendantRecord[i]["strnr"] != null && ja_AmendantRecord[i]["strnr"].ToString() != "")
                            { amendantrecord.strnr = ja_AmendantRecord[i]["strnr"].ToString(); ishave = true; }

                            if (ishave)
                            {
                                service.AddAmendantRecord(amendantrecord);
                            }
                        }
                        _message = "修改记录 导入成功!";
                        MessageShow(_message);
                    }
                }

            }
            catch (Exception ex)
            {
                //sb.Append(string.Format("导入流转记录报错，错误：{0}", ex.Message));
                _message = "附件修改记录 导入失败!" + personJson + "|" + ex.Message;
                WriteLogFile(_message);
            }
        }

        /// <summary>
        /// 关联文档
        /// </summary>
        /// <param name="DocumentID"></param>
        /// <param name="personJson"></param>
        /// <param name="service"></param>
        /// <param name="sjint"></param>
        /// <param name="sb"></param>
        protected void Import7(string DocumentID, string personJson, Service service, StringBuilder sb)
        {
            try
            {
                string AssociatedDocument = sjint.GETGLWDINFO(personJson);
                JObject jo_AssociatedDocument = (JObject)JsonConvert.DeserializeObject(AssociatedDocument);
                if (jo_AssociatedDocument["data"][0]["result"].ToString() == "success")
                {
                    string AssociatedDocument_info = jo_AssociatedDocument["data"][1]["info"].ToString();
                    JArray ja_AssociatedDocument = (JArray)JsonConvert.DeserializeObject(AssociatedDocument_info);
                    //JObject ja_AssociatedDocument = (JObject)JsonConvert.DeserializeObject(AssociatedDocument);
                    if (ja_AssociatedDocument.Count > 0)
                    {
                        AssociatedDocument associateddocument = new AssociatedDocument();
                        associateddocument.DocumentID = DocumentID;
                        for (int i = 0; i < ja_AssociatedDocument.Count; i++)
                        {
                            bool ishave = false;

                            associateddocument.AssociatedDocumentID = Guid.NewGuid();
                            //关联文档标题
                            if (ja_AssociatedDocument[i]["strText"] != null && ja_AssociatedDocument[i]["strText"].ToString() != "")
                            { associateddocument.strText = ja_AssociatedDocument[i]["strText"].ToString(); ishave = true; }
                            //关联文档unid
                            if (ja_AssociatedDocument[i]["strUnid"] != null && ja_AssociatedDocument[i]["strUnid"].ToString() != "")
                            { associateddocument.strUnid = ja_AssociatedDocument[i]["strUnid"].ToString(); ishave = true; }
                            //关联文档所在数据库路径
                            if (ja_AssociatedDocument[i]["strDbPath"] != null && ja_AssociatedDocument[i]["strDbPath"].ToString() != "")
                            { associateddocument.strDbPath = ja_AssociatedDocument[i]["strDbPath"].ToString(); ishave = true; }

                            if (ishave)
                            {
                                service.AddAssociatedDocument(associateddocument);
                            }
                        }
                        _message = "关联文档 导入成功!";
                        MessageShow(_message);
                    }
                }
            }
            catch (Exception ex)
            {
                //sb.Append(string.Format("导入流转记录报错，错误：{0}", ex.Message));
                _message = "关联文档 导入失败!" + personJson + "|" + ex.Message;
                WriteLogFile(_message);
            }
        }

        /// <summary>
        /// 公文评价
        /// </summary>
        /// <param name="DocumentID"></param>
        /// <param name="personJson"></param>
        /// <param name="service"></param>
        /// <param name="sjint"></param>
        /// <param name="sb"></param>
        protected void Import8(string DocumentID, string personJson, Service service, StringBuilder sb)
        {
            try
            {
                string EvaluationDocument = sjint.GETGWPJINFO(personJson);
                JObject jo_EvaluationDocument = (JObject)JsonConvert.DeserializeObject(EvaluationDocument);
                if (jo_EvaluationDocument["data"][0]["result"].ToString() == "success")
                {
                    string EvaluationDocument_info = jo_EvaluationDocument["data"][1]["info"].ToString();
                    JArray ja_EvaluationDocument = (JArray)JsonConvert.DeserializeObject(EvaluationDocument_info);
                    //JObject ja_AssociatedDocument = (JObject)JsonConvert.DeserializeObject(AssociatedDocument);
                    if (ja_EvaluationDocument.Count > 0)
                    {
                        EvaluationDocument evaluationdocument = new EvaluationDocument();
                        evaluationdocument.DocumentID = DocumentID;
                        for (int i = 0; i < ja_EvaluationDocument.Count; i++)
                        {
                            bool ishave = false;

                            evaluationdocument.EvaluationDocumentID = Guid.NewGuid();
                            //总计得分
                            if (ja_EvaluationDocument[i]["strzjdf"] != null && ja_EvaluationDocument[i]["strzjdf"].ToString() != "")
                            { evaluationdocument.strzjdf = ja_EvaluationDocument[i]["strzjdf"].ToString(); ishave = true; }
                            //扣分项目
                            if (ja_EvaluationDocument[i]["strkfxm"] != null && ja_EvaluationDocument[i]["strkfxm"].ToString() != "")
                            { evaluationdocument.strkfxm = ja_EvaluationDocument[i]["strkfxm"].ToString(); ishave = true; }


                            if (ishave)
                            {
                                service.AddEvaluationDocument(evaluationdocument);
                            }
                        }
                        _message = "公文评价 导入成功!";
                        MessageShow(_message);
                    }
                }
            }
            catch (Exception ex)
            {
                //sb.Append(string.Format("导入流转记录报错，错误：{0}", ex.Message));
                _message = "公文评价 导入失败!" + personJson + "|" + ex.Message;
                WriteLogFile(_message);
            }
        }

        /// <summary>
        /// 提醒记录
        /// </summary>
        /// <param name="DocumentID"></param>
        /// <param name="personJson"></param>
        /// <param name="service"></param>
        /// <param name="sjint"></param>
        /// <param name="sb"></param>
        protected void Import9(string DocumentID, string personJson, Service service, StringBuilder sb)
        {
            try
            {
                string ReminderLog = sjint.GETTXJLINFO(personJson);
                JObject jo_ReminderLog = (JObject)JsonConvert.DeserializeObject(ReminderLog);
                if (jo_ReminderLog["data"][0]["result"].ToString() == "success")
                {
                    string ReminderLog_info = jo_ReminderLog["data"][1]["info"].ToString();
                    JArray ja_ReminderLog = (JArray)JsonConvert.DeserializeObject(ReminderLog_info);
                    //JObject ja_AssociatedDocument = (JObject)JsonConvert.DeserializeObject(AssociatedDocument);
                    if (ja_ReminderLog.Count > 0)
                    {
                        ReminderLog reminderlog = new ReminderLog();
                        reminderlog.DocumentID = DocumentID;
                        for (int i = 0; i < ja_ReminderLog.Count; i++)
                        {
                            bool ishave = false;

                            reminderlog.ReminderLogID = Guid.NewGuid();
                            //内容
                            if (ja_ReminderLog[i]["strnr"] != null && ja_ReminderLog[i]["strnr"].ToString() != "")
                            { reminderlog.strnr = ja_ReminderLog[i]["strnr"].ToString(); ishave = true; }
                            //时间
                            if (ja_ReminderLog[i]["strsj"] != null && ja_ReminderLog[i]["strsj"].ToString() != "")
                            { reminderlog.strsj = ja_ReminderLog[i]["strsj"].ToString(); ishave = true; }
                            //用户
                            if (ja_ReminderLog[i]["stryh"] != null && ja_ReminderLog[i]["stryh"].ToString() != "")
                            { reminderlog.stryh = ja_ReminderLog[i]["stryh"].ToString(); ishave = true; }

                            if (ishave)
                            {
                                service.AddReminderLog(reminderlog);
                            }
                        }
                        _message = "提醒记录 导入成功!";
                        MessageShow(_message);
                    }
                }
            }
            catch (Exception ex)
            {
                //sb.Append(string.Format("导入流转记录报错，错误：{0}", ex.Message));
                _message = "提醒记录 导入失败!" + personJson + "|" + ex.Message;
                WriteLogFile(_message);
            }
        }

        /// <summary>
        /// 知会记录
        /// </summary>
        /// <param name="DocumentID"></param>
        /// <param name="personJson"></param>
        /// <param name="service"></param>
        /// <param name="sjint"></param>
        /// <param name="sb"></param>
        protected void Import10(string DocumentID, string personJson, Service service, StringBuilder sb)
        {
            try
            {
                string NotificationLog = sjint.GETZHIHUIINFO(personJson);
                JObject jo_NotificationLog = (JObject)JsonConvert.DeserializeObject(NotificationLog);
                if (jo_NotificationLog["data"][0]["result"].ToString() == "success")
                {
                    string NotificationLog_info = jo_NotificationLog["data"][1]["info"].ToString();
                    JArray ja_NotificationLog = (JArray)JsonConvert.DeserializeObject(NotificationLog_info);
                    //JObject ja_AssociatedDocument = (JObject)JsonConvert.DeserializeObject(AssociatedDocument);
                    if (ja_NotificationLog.Count > 0)
                    {
                        NotificationLog notificationlog = new NotificationLog();
                        notificationlog.DocumentID = DocumentID;
                        for (int i = 0; i < ja_NotificationLog.Count; i++)
                        {
                            bool ishave = false;

                            notificationlog.NotificationLogID = Guid.NewGuid();
                            //知会发送人
                            if (ja_NotificationLog[i]["strzhfsr"] != null && ja_NotificationLog[i]["strzhfsr"].ToString() != "")
                            { notificationlog.strzhfsr = ja_NotificationLog[i]["strzhfsr"].ToString(); ishave = true; }
                            //知会发送时间
                            if (ja_NotificationLog[i]["strzhfssj"] != null && ja_NotificationLog[i]["strzhfssj"].ToString() != "")
                            { notificationlog.strzhfssj = ja_NotificationLog[i]["strzhfssj"].ToString(); ishave = true; }
                            //知会接收人
                            if (ja_NotificationLog[i]["strzhjsr"] != null && ja_NotificationLog[i]["strzhjsr"].ToString() != "")
                            { notificationlog.strzhjsr = ja_NotificationLog[i]["strzhjsr"].ToString(); ishave = true; }
                            //知会阅读时间
                            if (ja_NotificationLog[i]["strzhydsj"] != null && ja_NotificationLog[i]["strzhydsj"].ToString() != "")
                            { notificationlog.strzhydsj = ja_NotificationLog[i]["strzhydsj"].ToString(); ishave = true; }
                            //知会阅读状态
                            if (ja_NotificationLog[i]["strzhydzt"] != null && ja_NotificationLog[i]["strzhydzt"].ToString() != "")
                            { notificationlog.strzhydzt = ja_NotificationLog[i]["strzhydzt"].ToString(); ishave = true; }
                            //知会操作动作
                            if (ja_NotificationLog[i]["strzhyj"] != null && ja_NotificationLog[i]["strzhyj"].ToString() != "")
                            { notificationlog.strzhyj = ja_NotificationLog[i]["strzhyj"].ToString(); ishave = true; }

                            if (ishave)
                            {
                                service.AddNotificationLog(notificationlog);
                            }
                        }
                        _message = "知会记录 导入成功!";
                        MessageShow(_message);
                    }
                }
            }
            catch (Exception ex)
            {
                //sb.Append(string.Format("导入流转记录报错，错误：{0}", ex.Message));
                _message = "知会记录 导入失败!" + personJson + "|" + ex.Message;
                WriteLogFile(_message);
            }
        }

        /// <summary>
        /// 发文跟踪
        /// </summary>
        /// <param name="DocumentID"></param>
        /// <param name="personJson"></param>
        /// <param name="service"></param>
        /// <param name="sjint"></param>
        /// <param name="sb"></param>
        protected void Import11(string DocumentID, string personJson, Service service, StringBuilder sb)
        {
            try
            {
                string DispatchTracking = sjint.GETFWGZINFO(personJson);
                JObject jo_DispatchTracking = (JObject)JsonConvert.DeserializeObject(DispatchTracking);
                if (jo_DispatchTracking["data"][0]["result"].ToString() == "success")
                {
                    string DispatchTracking_info = jo_DispatchTracking["data"][1]["info"].ToString();
                    JArray ja_DispatchTracking = (JArray)JsonConvert.DeserializeObject(DispatchTracking_info);
                    //JObject ja_AssociatedDocument = (JObject)JsonConvert.DeserializeObject(AssociatedDocument);
                    if (ja_DispatchTracking.Count > 0)
                    {
                        DispatchTracking dispatchtracking = new DispatchTracking();
                        dispatchtracking.DocumentID = DocumentID;
                        for (int i = 0; i < ja_DispatchTracking.Count; i++)
                        {
                            bool ishave = false;

                            dispatchtracking.DispatchTrackingID = Guid.NewGuid();
                            //接收部门
                            if (ja_DispatchTracking[i]["strjsbm"] != null && ja_DispatchTracking[i]["strjsbm"].ToString() != "")
                            { dispatchtracking.strjsbm = ja_DispatchTracking[i]["strjsbm"].ToString(); ishave = true; }
                            //接收人
                            if (ja_DispatchTracking[i]["strjsr"] != null && ja_DispatchTracking[i]["strjsr"].ToString() != "")
                            { dispatchtracking.strjsr = ja_DispatchTracking[i]["strjsr"].ToString(); ishave = true; }
                            //接收时间
                            if (ja_DispatchTracking[i]["strjssj"] != null && ja_DispatchTracking[i]["strjssj"].ToString() != "")
                            { dispatchtracking.strjssj = ja_DispatchTracking[i]["strjssj"].ToString(); ishave = true; }
                            //接收状态
                            if (ja_DispatchTracking[i]["strjszt"] != null && ja_DispatchTracking[i]["strjszt"].ToString() != "")
                            { dispatchtracking.strjszt = ja_DispatchTracking[i]["strjszt"].ToString(); ishave = true; }

                            if (ja_DispatchTracking[i]["strfssj"] != null && ja_DispatchTracking[i]["strfssj"].ToString() != "")
                            { dispatchtracking.strfssj = ja_DispatchTracking[i]["strfssj"].ToString(); ishave = true; }

                            if (ishave)
                            {
                                service.AddDispatchTracking(dispatchtracking);
                            }
                        }
                        _message = "发文跟踪 导入成功!";
                        MessageShow(_message);
                    }
                }
            }
            catch (Exception ex)
            {
                //sb.Append(string.Format("导入流转记录报错，错误：{0}", ex.Message));
                _message = "发文跟踪 导入失败!" + personJson + "|" + ex.Message;
                //WriteLogFile(_message);
            }
        }    

        #region 将json转换为DataTable
        /// <summary>
        /// 将json转换为DataTable
        /// </summary>
        /// <param name="strJson">得到的json</param>
        /// <returns></returns>
        private DataTable JsonToDataTable(string strJson)
        {
            //转换json格式
            strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
            //取出表名   
            var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名   
            strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            strJson = strJson.Substring(0, strJson.IndexOf("]"));
            //获取数据   
            rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split('*');
                //创建表   
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        var dc = new DataColumn();
                        string[] strCell = str.Split('#');
                        if (strCell[0].Substring(0, 1) == "\"")
                        {
                            int a = strCell[0].Length;
                            dc.ColumnName = strCell[0].Substring(1, a - 2);
                        }
                        else
                        {
                            dc.ColumnName = strCell[0];
                        }
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }
                //增加内容   
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    dr[r] = strRows[r].Split('#')[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }
            return tb;
        }
        #endregion

        public void MessageShow(String input)
        {
            SetControlText(this.textBox1, input);
        }



        //写入文本日志
        public void WriteLogFile(String input)
        {
            SetControlText(this.textBox1, input);

            //指定日志文件的目录
            string fname = ConfigurationManager.AppSettings["LogPath"];

            //定义文件信息对象 
            FileInfo finfo = new FileInfo(fname + "LogInfo" + LogDate + ".txt");

            //判断文件是否存在以及是否大于2K 
            if (finfo.Exists && finfo.Length > 20480000)
            {
                //删除该文件 
                finfo.Delete();
            }
            //创建只写文件流 
            using (FileStream fs = finfo.OpenWrite())
            {
                //根据上面创建的文件流创建写数据流 
                StreamWriter w = new StreamWriter(fs);
                //设置写数据流的起始位置为文件流的末尾 
                w.BaseStream.Seek(0, SeekOrigin.End);
                //写入当前系统时间并换行 
                w.Write("{0}\r\n ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                //写入日志内容并换行 
                w.Write(input + "\n ");
                //w.Write("--\n ");
                //清空缓冲区内容，并把缓冲区内容写入基础流 
                w.Flush();
                //关闭写数据流 
                w.Close();
            }
        }

        protected bool getTimeSpan()
        {
            //判断当前时间是否在工作时间段内
            string _strWorkingDayAM = ConfigurationManager.AppSettings["implementTime"];
            string _strWorkingDayPM = ConfigurationManager.AppSettings["closureTime"];

            DateTime t1 = Convert.ToDateTime(DateTime.Now.ToString());

            if (t1 > Convert.ToDateTime(_strWorkingDayAM) && t1 < Convert.ToDateTime(_strWorkingDayPM))
            {
                return true;
            }
            else
            {
                MessageShow("可执行时间为：" + _strWorkingDayAM + "至" + _strWorkingDayPM + ",当前时间为：" + DateTime.Now.ToString("HH:mm:ss") + ",此程序不能执行！");
                Thread.Sleep(60000);
                return false;
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(DataLeadinginEx);
            //ThreadPool.QueueUserWorkItem(DataLeadinginEx);
        }
    }
}
